<?php
namespace Zeke\Io\Loop;


/**
 * Class SignalsHandler
 * @package Zeke\Io\Loop
 */
final class SignalsHandler
{



    private $signals = array();


    /**
     * 添加到信号队列
     *
     * @param $signal
     * @param $listener
     *
     * @author <liu.bin@ruaby.com> 2018-08-19 21:58
     */
    public function add($signal, $listener)
    {
        if (!isset($this->signals[$signal])) {
            $this->signals[$signal] = array();
        }
        if (\in_array($listener, $this->signals[$signal])) {
            return;
        }
        $this->signals[$signal][] = $listener;
    }


    /**
     * 移除信号队列
     *
     * @param $signal
     * @param $listener
     *
     * @author <liu.bin@ruaby.com> 2018-08-19 21:59
     */
    public function remove($signal, $listener)
    {
        if (!isset($this->signals[$signal])) {
            return;
        }
        $index = \array_search($listener, $this->signals[$signal], true);
        unset($this->signals[$signal][$index]);
        if (isset($this->signals[$signal]) && \count($this->signals[$signal]) === 0) {
            unset($this->signals[$signal]);
        }
    }


    /**
     * 信号调用回调函数
     *
     * @param $signal
     *
     * @author <liu.bin@ruaby.com> 2018-08-19 21:59
     */
    public function call($signal)
    {
        if (!isset($this->signals[$signal])) {
            return;
        }
        foreach ($this->signals[$signal] as $listener) {
            \call_user_func($listener, $signal);
        }
    }


    /**
     * 注册信号的回调总数
     *
     * @param $signal
     * @return int
     *
     * @author <liu.bin@ruaby.com> 2018-08-19 21:59
     */
    public function count($signal)
    {
        if (!isset($this->signals[$signal])) {
            return 0;
        }
        return \count($this->signals[$signal]);
    }


    /**
     * 是否注册过信号事件
     *
     * @return bool
     *
     * @author <liu.bin@ruaby.com> 2018-08-19 22:00
     */
    public function isEmpty()
    {
        return !$this->signals;
    }
}